package org.yray.io.facedetect.service;

import org.opencv.core.*;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
import org.opencv.objdetect.CascadeClassifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.UUID;

import static org.bytedeco.javacpp.opencv_objdetect.CASCADE_DO_CANNY_PRUNING;

@Service
public class DetectService {

    @Value("${opencv.model-path}")
    private String modelPath;

    @Value("${web.upload-path:D}")
    private String uploadPath;

    public Rect[] rects(Mat srcImg,int minneighbors)
    {


        // 目标灰色图像
        Mat dstGrayImg = new Mat();
        // 转换灰色
        Imgproc.cvtColor(srcImg, dstGrayImg, Imgproc.COLOR_BGR2GRAY);
        // OpenCv人脸识别分类器
        CascadeClassifier classifier = new CascadeClassifier(modelPath);
        // 用来存放人脸矩形
        MatOfRect faceRect = new MatOfRect();

        // 特征检测点的最小尺寸
        Size minSize = new Size(32, 32);
        // 图像缩放比例,可以理解为相机的X倍镜
        double scaleFactor = 1.2;
        // 执行人脸检测
        classifier.detectMultiScale(dstGrayImg, faceRect, scaleFactor, minneighbors, CASCADE_DO_CANNY_PRUNING, minSize);
        //遍历矩形,画到原图上面


        Rect[] rects = faceRect.toArray();

        return rects;
    }

    public String saveImg(Rect[] rects,Mat srcImg )
    {
        // 定义绘制颜色
        Scalar color = new Scalar(0, 0, 255);
        // 逐个处理
        for(Rect rect: rects) {
            int x = rect.x;
            int y = rect.y;
            int w = rect.width;
            int h = rect.height;
            // 单独框出每一张人脸
            Imgproc.rectangle(srcImg, new Point(x, y), new Point(x + w, y + w), color, 2);
        }

        // 添加人脸框之后的图片的名字
        String newFileName = UUID.randomUUID().toString() + ".png";

        // 保存
        Imgcodecs.imwrite(uploadPath + "/" + newFileName, srcImg);
        return newFileName;
    }
}
